package com.atguigu.education.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.education.bean.NewUserBean;
import com.atguigu.education.bean.PayBean;
import com.atguigu.education.util.ClickHouseUtil;
import com.atguigu.education.util.DateFormatUtil;
import com.atguigu.education.util.KafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author luyang
 * @create 2022/9/6 19:42
 */
public class DwsPlayWindow {
    public static void main(String[] args) throws Exception {
        // TODO 1 环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // TODO 2 设置状态后端
        /*
        env.enableCheckpointing(5 * 60 * 1000L, CheckpointingMode.EXACTLY_ONCE );
        env.getCheckpointConfig().setCheckpointTimeout( 3 * 60 * 1000L );
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        System.setProperty("HADOOP_USER_NAME", "atguigu");
         */
        String topicName = "dwd_pay_chapter_user";
        String groupID = "dws_play_window";
        DataStreamSource<String> orderSource = env.addSource(KafkaUtil.getKafkaConsumer(topicName,groupID ));
        //orderSource.print();
        // TODO 4、将数据进行转化
        SingleOutputStreamOperator<JSONObject> mapStream0 = orderSource.map(new MapFunction<String, JSONObject>() {
            @Override
            public JSONObject map(String value) throws Exception {
                return JSONObject.parseObject(value);
            }
        });
        SingleOutputStreamOperator<PayBean> mapStream = mapStream0.map(new MapFunction<JSONObject, PayBean>() {
            @Override
            public PayBean map(JSONObject value) throws Exception {
                JSONObject appVideo = value.getJSONObject("appVideo");
                return new PayBean("", "", 1L, appVideo.getLong("play_sec"), 1L, 0L, value.getLong("ts"));
            }
        });
        // TODO 5、设置水位线
        SingleOutputStreamOperator<PayBean> watermarks = mapStream.assignTimestampsAndWatermarks(WatermarkStrategy.<PayBean>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(new SerializableTimestampAssigner<PayBean>() {
            @Override
            public long extractTimestamp(PayBean element, long recordTimestamp) {
                return element.getTs();
            }
        }));
        //TODO 6、开窗
        SingleOutputStreamOperator<PayBean> reduce = watermarks.windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<PayBean>() {
                    @Override
                    public PayBean reduce(PayBean value1, PayBean value2) throws Exception {
                        value1.setPayTime(value1.getPayTime() + value2.getPayTime());
                        value1.setPayCount(value1.getPayCount() + value2.getPayCount());
                        value1.setPeopleCount(value1.getPeopleCount() + value2.getPeopleCount());
                        return value1;
                    }
                }, new AllWindowFunction<PayBean, PayBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<PayBean> values, Collector<PayBean> out) throws Exception {
                        PayBean userRegisterBean = values.iterator().next();
                        userRegisterBean.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                        userRegisterBean.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                        userRegisterBean.setTs(System.currentTimeMillis());
                        userRegisterBean.setAvgTimeCount(userRegisterBean.getPayTime()/userRegisterBean.getPeopleCount());
                        out.collect(userRegisterBean);
                    }
                });
        reduce.print(">>");
        //TODO 7、写进Clickhouse
        reduce.addSink(ClickHouseUtil.getClickHouseSinkFunc("insert into dws_play_window values(?,?,?,?,?,?,?)"));
        //TODO 执行
        env.execute();

        //TODO 执行
        env.execute();
    }
}
